
PARAM ( [switch]$Clean )

Start-Transcript $Env:SystemRoot\Temp\DiskPartitions.log
$OSDiskNr = (gwmi win32_diskpartition | ? { $_.BootPartition } ).DiskIndex
$Disks = Get-WmiObject Win32_DiskDrive -Filter "Index <> $OsDiskNr"

Function RunDiskpartScript ( $Script ) {
    Write-Output "`n******************************"
    Write-Output $Script
    Write-Output "******************************"
    $Script | Diskpart.exe
    Start-Sleep -Seconds 2
}


ForEach ($Disk in $Disks ) {
  if (($Disk.Partitions -eq 0) -or $Clean) {

  switch ($Disk.Index) {
    1 { $Letter="D" ; $Label="Programs" }
    2 { $Letter="P" ; $Label="PageFile" }
    default { $Letter = $Nul }
  }

  if ($Letter) {
    if ( Get-WmiObject Win32_Volume -Filter "caption = '$($Letter):\\'" ) {
        Write-Output "Volume $Letter already exists... Skipping !"
    } else {

        Write-Output "Disk $($Disk.Index) Letter $Letter Label $Label"

        if ($Clean) {
          Write-Output "Cleaning disk $($Disk.Index) ... "
          $DPScript = @"
Select disk $($Disk.Index)
Clean
"@
          RunDiskPartScript $DPScript
        }

        $DPScript = @"
Select disk $($Disk.Index)
online disk noerr
attributes disk clear readonly noerr
create partition primary noerr
"@
          RunDiskPartScript $DPScript
 
          $DPScript = @"
Select disk $($Disk.Index)
Select Partition 1
Format FS=NTFS Label=$Label quick noerr
assign letter $Letter
"@
          RunDiskPartScript $DPScript

        }
    }

  } else {
    Write-Output "Disk $($Disk.Index) already has $($Disk.Partitions) partitions"
  }
}

Stop-Transcript

